package edu.wayne.cs.csc4110.hw6.framework.state;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

import edu.wayne.cs.csc4110.hw6.framework.user.BaseUser;
import edu.wayne.cs.csc4110.hw6.interfaces.state.UserState;
import edu.wayne.cs.csc4110.hw6.interfaces.user.User;

public class UserStateImpl implements UserState, Serializable {


	private static final String EXTENSION = ".user";
	private static final String DIRECTORY = "/Temp/users/";
	private File userFile;
	private String username;
	private String pluginExtension;

	public UserStateImpl(String username, String pluginExtension) {
		this.username = username;
		this.pluginExtension = pluginExtension;
		userFile = new File(DIRECTORY + this.username + EXTENSION+ this.pluginExtension);
	}

	/**
	 * @param out
	 *            if null uses default file structure for storing users.
	 * 
	 */
	@Override
	public boolean storeState(OutputStream out, Object obj) throws IOException {

		if (out != null) {
			if (out instanceof ObjectOutputStream) {
				((ObjectOutputStream) out).writeObject(obj);
				out.close();
			} else if (out instanceof FileOutputStream) {

				ObjectOutputStream storeUser = new ObjectOutputStream(out);
				storeUser.writeObject(obj);
				storeUser.close();
				out.close();
			} else {
				throw new IllegalArgumentException(out + ": Not Supported");
			}
		} else {
			userFile.createNewFile();

			FileOutputStream userFos = new FileOutputStream(userFile);
			ObjectOutputStream storeUser = new ObjectOutputStream(userFos);
			storeUser.writeObject(obj);
			storeUser.close();
			userFos.close();
			return true;
		}
		return false;

	}

	@Override
	public User createState(InputStream in) throws ClassNotFoundException,
			IOException {
		User u;
		if (in != null) {
			if (in instanceof ObjectInputStream) {
				u = (BaseUser) ((ObjectInputStream) in).readObject();
				in.close();
			} else if (in instanceof FileInputStream) {
				ObjectInputStream createUser = new ObjectInputStream(in);
				u = (BaseUser) createUser.readObject();
				createUser.close();
				in.close();
			} else {
				throw new IllegalArgumentException(in + ": Not Supported");
			}
		} else {
			// restore from default user state

			FileInputStream userIn = new FileInputStream(userFile);
			ObjectInputStream createUser = new ObjectInputStream(userIn);

			u = (BaseUser) createUser.readObject();

			userIn.close();
			createUser.close();

		}

		return u;

	}
	
	public class UserFileFilter implements FilenameFilter {

		@Override
		public boolean accept(File dir, String name) {
			return name.contains(EXTENSION);
		}

	}

}
